<template>
  <view class="page">
    <u-form
      :model="registerForm"
      ref="formRef"
      label-position="top"
      :border-bottom="false"
      :label-style="labelStyle"
      :placeholder-style="placeholderStyle"
    >
      <u-form-item label="归属服务商" prop="belongService">
        <u-input
          v-model="belongDisplayValue"
          type="select"
          @click="showServiceSelect = true"
          :select-open="showServiceSelect"
          :border="true"
          :border-color="borderColor"
          placeholder="请选择归属服务商"
        />
        <u-select
          v-model="showServiceSelect"
          mode="single-column"
          :list="belongOptions"
          label-name="label"
          value-name="value"
          @confirm="belongSelect"
          :defaultValue="[currentBelongIndex]"
        >
        </u-select>
      </u-form-item>
      <u-form-item label="商户名称（企业名称）" prop="merchantName"
        ><u-input v-model="registerForm.merchantName" border :border-color="borderColor" placeholder="请输入名称"
      /></u-form-item>

      <u-form-item label="归属地市" prop="belongCity">
        <u-input
          v-model="belongCityDisplayValue"
          type="select"
          @click="showBelongCitySelect = true"
          :select-open="showBelongCitySelect"
          :border="true"
          :border-color="borderColor"
          placeholder="请选择归属地市"
        />
        <u-select
          v-model="showBelongCitySelect"
          mode="single-column"
          :list="belongCityOptions"
          label-name="label"
          value-name="value"
          @confirm="belongAreaSelect"
          :defaultValue="[currentBelongCityIndex]"
        >
        </u-select>
      </u-form-item>
    </u-form>

    <!-- 实名认证 -->
    <view class="label_title">实名认证</view>

    <view class="verify_form">
      <u-form :model="verifyForm" ref="verifyRef" :label-width="180" :label-style="verifyLabelStyle">
        <u-form-item label="国籍" prop="nationality">
          <u-input
            v-model="nationDisplayValue"
            type="select"
            @click="showNationSelect = true"
            :select-open="showNationSelect"
            :border-color="borderColor"
          />
          <u-select
            v-model="showNationSelect"
            mode="single-column"
            :list="nationOptions"
            label-name="label"
            value-name="value"
            @confirm="nationSelect"
            :defaultValue="[currentNationIndex]"
          >
          </u-select>
        </u-form-item>
        <u-form-item label="姓名" prop="userName"
          ><u-input v-model="verifyForm.userName" :border-color="borderColor" placeholder="请输入姓名"
        /></u-form-item>

        <u-form-item label="证件类型" prop="idType">
          <u-input
            v-model="idTypeDisplayValue"
            type="select"
            @click="showIdTypeSelect = true"
            :select-open="showIdTypeSelect"
            :border-color="borderColor"
          />
          <u-select
            v-model="showIdTypeSelect"
            mode="single-column"
            :list="idTypeOptions"
            label-name="label"
            value-name="value"
            @confirm="idTypeSelect"
            :defaultValue="[currentIdTypeIndex]"
          >
          </u-select>
        </u-form-item>
        <u-form-item label="证件号" prop="idNum"
          ><u-input type="number" v-model="verifyForm.idNum" :border-color="borderColor" placeholder="请输入证件号"
        /></u-form-item>
        <u-form-item type="number" label="联系电话" prop="phone"
          ><u-input v-model="verifyForm.phone" :border-color="borderColor" placeholder="请输入联系电话"
        /></u-form-item>
        <u-form-item type="number" label="银行卡号" prop="bankCardNum"
          ><u-input v-model="verifyForm.bankCardNum" :border-color="borderColor" placeholder="请输入银行卡号"
        /></u-form-item>

        <!-- 身份证正面  -->
        <view class="upload_box">
          <image
            class="bg"
            :style="{ 'z-index': isImgUploaded1 ? 0 : 2 }"
            src="/static/form/z_front.png"
            mode="widthFix"
          ></image>
          <u-upload
            width="calc(100vw - 120rpx)"
            height="calc((100vw - 120rpx) * 0.4414)"
            ref="upload1"
            :auto-upload="false"
            max-count="1"
            :action="UPLOAD_URL"
            :file-list="fileList1"
            @on-list-change="handleListChange"
            @on-uploaded="onUploaded1"
            :header="uploadHeader"
          >
          </u-upload>
        </view>

        <!-- 身份证反面  -->
        <view class="upload_box">
          <image
            class="bg"
            :style="{ 'z-index': isImgUploaded2 ? 0 : 2 }"
            src="/static/form/z_back.png"
            mode="widthFix"
          ></image>
          <u-upload
            width="calc(100vw - 120rpx)"
            height="calc((100vw - 120rpx) * 0.4414)"
            ref="upload2"
            :auto-upload="false"
            max-count="1"
            :action="UPLOAD_URL"
            :file-list="fileList2"
            @on-list-change="handleListChange2"
            @on-uploaded="onUploaded2"
            :header="uploadHeader"
          >
          </u-upload>
        </view>

        <!-- 营业执照上传  -->
        <view class="upload_box2">
          <view class="hover_box" :style="{ 'z-index': isImgUploaded3 ? 0 : 2 }">
            <image class="img" src="/static/form/add.png" mode="aspectFill"></image>
          </view>
          <u-upload
            width="calc(100vw - 120rpx)"
            height="calc((100vw - 120rpx) * 0.4414)"
            ref="upload3"
            :auto-upload="false"
            max-count="1"
            :action="UPLOAD_URL"
            :file-list="fileList3"
            @on-list-change="handleListChange3"
            @on-uploaded="onUploaded3"
            :header="uploadHeader"
          >
          </u-upload>
        </view>

        <view class="upload_tip">请上传营业执照/品牌授权书</view>
      </u-form>
    </view>
    <view class="submit" @click="submit">提交审核</view>
    <view
      class="safe_area"
      :style="{
        height: '80rpx',
      }"
    ></view>
  </view>
</template>

<script setup>
  import { ref, reactive, computed } from 'vue';
  import { onShow, onLoad } from '@dcloudio/uni-app';
  import { useFormStore } from '../../store/form';
  import { getCityOptions, addMerchant } from '../../apis/pages';
  import { UPLOAD_URL } from '../../config/config';
  import { useUserStore } from '../../store/user';

  const userStore = useUserStore();

  const formStore = useFormStore();
  const { merchantForm } = formStore; // 商户表

  const formRef = ref();
  const registerForm = reactive({
    belongService: '', // 归属服务商
    merchantName: '', // 商户名称
    belongCity: '', // 归属地市
  });

  const verifyRef = ref();
  const verifyForm = reactive({
    nationality: '中国',
    userName: '', //姓名
    idType: '身份证', //证件类型
    idNum: '', //证件号
    bankCardNum: '', //银行卡号
    phone: '', //联系电话
  });

  const uploadForm = reactive({
    idFaceImage: '', //人脸面
    idNationalImage: '', //国徽面
    merchantInfoImage: '', //营业执照
  });

  // 三个上传完成标志
  const uploadStatus = reactive({
    idFaceImageUploaded: false,
    idNationalImageUploaded: false,
    merchantInfoImageUploaded: false,
  });

  function resetUploadStatus() {
    uploadStatus.idFaceImageUploaded = false;
    uploadStatus.idNationalImageUploaded = false;
    uploadStatus.merchantInfoImageUploaded = false;
  }

  const isSubmit = ref(false);

  const borderColor = '#747474';

  // 上传相关
  const upload1 = ref();
  const upload2 = ref();
  const upload3 = ref();
  // const uploadUrl = ref('http://192.168.1.1:8080/upload');
  const uploadHeader = {
    authorization: 'Bearer ' + userStore.token,
  };

  // 图片1 是否上传了
  const isImgUploaded1 = ref(false);
  const fileList1 = ref([]);

  const isImgUploaded2 = ref(false);
  const fileList2 = ref([]);

  const isImgUploaded3 = ref(false);
  const fileList3 = ref([]);

  // form 样式相关

  const labelStyle = {
    'font-weight': 600,
    'font-size': '30rpx',
    color: '#1E2737',
  };

  const placeholderStyle = {
    'font-weight': 500,
    'font-size': '26rpx',
    color: '#989898',
  };

  const verifyLabelStyle = {
    'font-weight': 500,
    'font-size': '26rpx',
    color: '#989898',
  };

  // 归属服务商
  const showServiceSelect = ref(false);
  const belongDisplayValue = ref('');
  const currentBelongIndex = ref(0);
  const belongOptions = [
    {
      label: 'jfsdyy 积分时代',
      value: 'jfsdyy',
    },
    {
      label: 'nstpyy 南山拓扑',
      value: 'nstpyy',
    },
  ];

  // 归属城市
  const showBelongCitySelect = ref(false);
  const belongCityDisplayValue = ref('');
  const currentBelongCityIndex = ref(0);
  const belongCityOptions = ref([
    // {
    //   label: '上海',
    //   value: '1',
    // },
    // {
    //   label: '南京',
    //   value: '2',
    // },
  ]);

  // 国籍
  const showNationSelect = ref(false);
  const nationDisplayValue = ref('中国');
  const currentNationIndex = ref(0);
  const nationOptions = [
    {
      label: '中国',
      value: '中国',
    },
  ];

  // 证件类型
  const showIdTypeSelect = ref(false);
  const idTypeDisplayValue = ref('身份证');
  const currentIdTypeIndex = ref(0);
  const idTypeOptions = [
    {
      label: '身份证',
      value: '身份证',
    },
  ];

  onLoad(() => {
    console.log('onLoad');
    // 获取地市下拉
    getCitys();
  });

  // 获取地市下拉
  function getCitys() {
    getCityOptions().then((res) => {
      belongCityOptions.value = [];
      Object.entries(res).forEach(([key, value]) => {
        belongCityOptions.value.push({
          label: value,
          value: key,
        });
      });
    });
  }

  function belongSelect(e) {
    registerForm.belongService = e[0].value;
    showServiceSelect.value = false;
    currentBelongIndex.value = e[0].index;
    belongDisplayValue.value = e[0].label;
  }

  function belongAreaSelect(e) {
    registerForm.belongCity = e[0].value;
    showBelongCitySelect.value = false;
    currentBelongCityIndex.value = e[0].index;
    belongCityDisplayValue.value = e[0].label;
  }

  function nationSelect(e) {
    verifyForm.nationality = e[0].value;
    showNationSelect.value = false;
    currentNationIndex.value = e[0].index;
    nationDisplayValue.value = e[0].label;
  }

  function idTypeSelect(e) {
    verifyForm.idType = e[0].value;
    showIdTypeSelect.value = false;
    currentIdTypeIndex.value = e[0].index;
    idTypeDisplayValue.value = e[0].label;
  }

  function beforeUpload(index, list) {
    console.log('index >>>', index);
    console.log('list >>>', list);
  }

  // 上传组件本地图片列表变化
  function handleListChange(n) {
    if (upload1.value.lists.length > 0) {
      isImgUploaded1.value = true;
    } else {
      isImgUploaded1.value = false;
    }
  }

  function handleListChange2(n) {
    if (upload2.value.lists.length > 0) {
      isImgUploaded2.value = true;
    } else {
      isImgUploaded2.value = false;
    }
  }
  function handleListChange3(n) {
    if (upload3.value.lists.length > 0) {
      isImgUploaded3.value = true;
    } else {
      isImgUploaded3.value = false;
    }
  }

  function onUploaded1(list) {
    uploadForm.idFaceImage = list[0].response.data;
    uploadStatus.idFaceImageUploaded = true;
    checkAllUploaded();
  }

  function onUploaded2(list) {
    uploadForm.idNationalImage = list[0].response.data;
    uploadStatus.idNationalImageUploaded = true;
    checkAllUploaded();
  }

  function onUploaded3(list) {
    uploadForm.merchantInfoImage = list[0].response.data;
    uploadStatus.merchantInfoImageUploaded = true;
    checkAllUploaded();
  }
  function submit() {
    if (isSubmit.value) return;
    // 手动调用图片上传 在回调中检查是否所有都传完 最后合并表单数据
    console.log(merchantForm, 'merchantForm >>>');
    console.log(verifyForm, 'verifyForm >>>');
    console.log(registerForm, 'registerForm >>>');

    if (upload1.value.lists.length && upload2.value.lists.length && upload3.value.lists.length) {
      isSubmit.value = true;
      uni.showLoading({
        title: '提交中...',
        mask: true,
      });
      upload1.value.upload();
      upload2.value.upload();
      upload3.value.upload();
    } else {
      mergeForm();
    }
  }

  // 检查是否全部上传完
  function checkAllUploaded() {
    const allUploaded = Object.values(uploadStatus).every((status) => status);

    if (allUploaded) {
      isSubmit.value = false;
      uni.hideLoading();
      resetUploadStatus();
      mergeForm();
    }
  }

  // 合并表单
  function mergeForm() {
    console.log('所有图片上传成功，可以合并数据了');

    formStore.merchantForm = {
      ...formStore.merchantForm,
      ...registerForm,
      ...verifyForm,
      ...uploadForm,
    };

    console.log('最终提交的数据：', formStore.merchantForm);

    addMerchant(formStore.merchantForm).then((res) => {
      console.log(res, 'res >>>');
      if (res.code == 200) {
        uni.reLaunch({ url: '/pagesB/register/finish' });
      }
    });
  }
</script>

<style scoped lang="scss">
  // /deep/ .u-form-item {
  //   padding-bottom: 0 !important;
  // }

  .page {
    width: 100vw;
    min-height: 100vh;
    padding: 40rpx;
    box-sizing: border-box;
    font-size: 28rpx;
    background-color: #f5f5f5;
  }

  .content {
    background-color: #fff;
    padding: 20rpx;
    border-radius: 16rpx;
    box-sizing: border-box;
    margin-bottom: 30rpx;
  }

  .label_title {
    font-weight: 600;
    font-size: 30rpx;
    color: #1e2737;
    margin-bottom: 30rpx;
  }

  .verify_form {
    padding: 0 20rpx;
  }

  .upload_box {
    position: relative;
    width: 100%;
    margin-bottom: 20rpx;
    .bg {
      position: absolute;
      top: 0;
      left: 0;
      width: calc(100vw - 120rpx);
      height: calc((100vw - 120rpx) * 0.4414);
      z-index: 2;
      pointer-events: none;
    }
  }

  .upload_box2 {
    position: relative;
    width: 100%;
    border-radius: 20rpx;
    overflow: hidden;
    margin-bottom: 20rpx;

    .hover_box {
      display: flex;
      align-items: center;
      justify-content: center;
      position: absolute;
      top: 0;
      left: 0;
      width: calc(100vw - 120rpx);
      height: calc((100vw - 120rpx) * 0.4414);
      z-index: 2;
      pointer-events: none;
      background-color: #e5e5e5;

      .img {
        width: 102rpx;
        height: 102rpx;
      }
    }
  }

  .upload_tip {
    font-weight: 500;
    font-size: 26rpx;
    color: #989898;
    text-align: center;
    margin-bottom: 60rpx;
  }

  .submit {
    width: 537rpx;
    height: 83rpx;
    background: #016bec;
    border-radius: 10rpx;

    font-weight: 500;
    font-size: 30rpx;
    color: #ffffff;

    text-align: center;
    line-height: 83rpx;
    margin: 0 auto;
  }
</style>
